package com.hc.controller;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.domain.User;
import com.hc.jwt.JwtConst;
import com.hc.jwt.JwtUtil;
import com.hc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping(value = "/login")
    public Result userLogin(@RequestParam(name = "username", required = true) String username,
                            @RequestParam(name = "password", required = true) String password,
                            HttpServletResponse response) {
        User user = userService.getUserByUsername(username);
        // 用户不存在
        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }

        // 用户被锁定
        if (user.getLocked()) {
            throw new LockedAccountException("该用户已被锁定，暂时无法登录！");
        }

        if(!user.getPassword().equals(JwtUtil.saltPassword(password,user.getSalt()))){
            throw new IncorrectCredentialsException("密码不匹配，请检查后重新输入！");
        }

        // 若登录成功，签发 JWT token
        String jwtToken = JwtUtil.createToken(username, JwtConst.SECRET);
        // 将签发的 JWT token 设置到 HttpServletResponse 的 Header 中
        System.out.println("jwtToken:  " + jwtToken);
        response.setHeader(JwtConst.AUTH_HEADER, jwtToken);
        response.setHeader("Access-control-Expose-Headers", "x-auth");

        return  ResultUtil.success("登录成功",user);
    }

    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        //在这里执行退出系统前需要清空的数据
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
            subject.logout();
        }
        System.out.println("退出登录成功");
        return ResultUtil.success("退出登录");
    }

}
